<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="headerShow">
                <a-form ref="formRef" layout="horizontal" :model="dataForm" :label-col-props="{ span: 8 }"
                    :wrapper-col-props="{ span: 16 }">
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="需求申请部门" field="needDepartment"
                                :rules="[{ required: true, message: '部门必填' }]" :validate-trigger="['change', 'blur']">
                                <a-input :style="{ width: '22rem' }" v-model="dataForm.needDepartment" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="开单日期">
                                <a-input disabled :style="{ width: '22rem' }" v-model="dataForm.needCreateDate" />
                            </a-form-item>
                        </a-col>

                        <a-col :span="6">
                            <a-form-item label="需求人">
                                <a-input disabled v-model="dataForm.needPerson" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="需求单号">
                                <a-input disabled v-model="dataForm.purchaseNeedCode" />
                            </a-form-item>
                        </a-col>


                    </a-row>
                    <a-row :gutter="16">
                        <a-col :span="6">

                            <a-form-item label="需求单类型" field="needType" :rules="[{ required: true, message: '需求类型必选' }]"
                                :validate-trigger="['change', 'blur']">
                                <!-- <a-input :style="{ width: '22rem' }" placeholder="请输入需求类型" v-model="dataForm.needType" /> -->
                                <a-select popup-container="html"  v-model="dataForm.needType">
                                    <a-option>加急</a-option>
                                    <a-option>计划</a-option>
                                    <a-option>临时</a-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="仓库名称">
                                <a-select popup-container="html"  :loading="loading" @search="handleSearchz" v-model="dataForm.warehouseName"
                                    :filter-option="false" allow-search allow-clear @focus="focusSelz">
                                    <a-option v-for="item in pageData.nameListz as any" :value="item.warehouseName">{{
                                            item.warehouseName
                                    }}</a-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="采购部门" field="useDepartment"
                                :rules="[{ required: true, message: '采购部门必填' }]" :validate-trigger="['change', 'blur']">
                                <a-input v-model="dataForm.useDepartment" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="需求说明" field="needInstruction">
                                <a-input v-model="dataForm.needInstruction" />
                            </a-form-item>
                        </a-col>
                    </a-row>

                </a-form>
            </div>
              <div class="my-divisders">
            <a-divider orientation="center">
                <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
            </a-divider>
             </div>
            <div class="my-tool-bar">
                <Toolbar :items="pageData.btnList" @tjWl="tjWl" @del="scWl" @delQk="delQk" @addXqiu="addXqiu">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane title="创建需求单">
                    <!-- <a-space>
                        <a-button type="outline" @click="tjWl" v-if="pageData.isTjwl">添加物料</a-button>
                        <a-button type="outline" @click="scWl" v-if="pageData.isScWl">删除</a-button>
                    </a-space> -->
                    <a-table :style="{
                        height: pageData.rHeight - 150 + 'px',
                        marginTop: '10px'
                    
                    }" stripe :bordered="true" :columns="tableColumns1" :data="isDataLists"
                        v-model:selected-keys="selectedRowKeys1" row-key="materialName"
                        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }">
                    </a-table>
                    <!-- <div class="isAdd">
                        <a-space>
                            <a-button type="outline" @click="delQk" v-if="pageData.isDel">清空</a-button>
                            <a-button type="primary" @click="addXqiu" v-if="pageData.isQr">确认</a-button>
                        </a-space>
                    </div> -->
                </a-tab-pane>
            </a-tabs>
        </template>
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :width="400"
            popup-container=".arco-tabs-content" :height="pageData.rHeight + 80" placement="bottom"
            :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="cancelsDel">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="vertical" :model="dataForm">
                    <!-- <a-form-item label="编号" field="settlementCode"
                    :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input placeholder="请输入编号" v-model="dataForm.settlementCode" @blur="inputBlur" />
                </a-form-item> -->
                    <a-space>
                        <a-form-item label="需求部门" field="needDepartment" :rules="[{ required: true, message: '部门必填' }]"
                            :validate-trigger="['change', 'blur']">
                            <a-input :style="{ width: '22rem' }" placeholder=""
                                v-model="dataForm.needDepartment" />
                        </a-form-item>
                        <a-form-item label="开单日期" field="needCreateDate" :rules="[{ required: true, message: '日期必填' }]"
                            :validate-trigger="['change', 'blur']">
                            <a-date-picker  popup-container="html"  style="width: 22rem;" :time-picker-props="{ defaultValue: '00:00:00' }"
                                format="YYYY-MM-DD" v-model="dataForm.needCreateDate" />
                        </a-form-item>
                        <a-form-item label="开单日期">
                            <a-input disabled :style="{ width: '22rem' }" v-model="dataForm.needCreateDate" />
                        </a-form-item>
                        <a-form-item label="需求人" field="needPerson" :rules="[{ required: true, message: '需求人必填' }]"
                            :validate-trigger="['change', 'blur']">
                            <a-input :style="{ width: '22rem' }" placeholder="" v-model="dataForm.needPerson" />
                        </a-form-item>

                        <a-form-item label="需求单号">
                            <a-input disabled :style="{ width: '22rem' }" />
                        </a-form-item>
                    </a-space>
                    <a-space>
                        <a-form-item label="需求类型" field="needType" :rules="[{ required: true, message: '需求类型必填' }]"
                            :validate-trigger="['change', 'blur']">
                            <a-input :style="{ width: '22rem' }" placeholder="" v-model="dataForm.needType" />
                        </a-form-item>
                        <a-form-item label="仓库名称">
                            <a-select popup-container="html"  :style="{ width: '22rem' }" :loading="loading" placeholder=""
                                @search="handleSearchz" v-model="dataForm.warehouseName" :filter-option="false"
                                allow-search allow-clear @focus="focusSelz">
                                <a-option v-for="item in pageData.nameListz as any" :value="item.warehouseName">{{
                                        item.warehouseName
                                }}</a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="采购部门" field="useDepartment" :rules="[{ required: true, message: '采购部门必填' }]"
                            :validate-trigger="['change', 'blur']">
                            <a-input :style="{ width: '22rem' }" placeholder=""
                                v-model="dataForm.useDepartment" />
                        </a-form-item>
                    </a-space>
                    <a-form-item label="需求说明" field="needInstruction">
                        <a-input :style="{ width: '96rem' }" placeholder="" v-model="dataForm.needInstruction" />
                    </a-form-item>
                </a-form>
            </div>
            <a-space>
                <a-button type="outline" @click="tjWl" v-if="pageData.isTjwl">添加物料</a-button>
                <a-button type="outline" @click="scWl" v-if="pageData.isScWl">删除</a-button>
            </a-space>
            <a-table :style="{
                height: pageData.rHeight + 'px',
                marginTop: '10px'
            }" :scrollbar="true" sticky-header stripe :bordered="true" :columns="tableColumns1" :data="isDataLists"
                v-model:selected-keys="selectedRowKeys1" row-key="materialName"
                :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }">
            </a-table>
        </a-drawer>

        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" :width="400"
            :visible="pageData1.showAdd" unmountOnClose @ok="sideOks" @cancel="pageData1.showAdd = false">
            <template #title>
                {{ pageData1.title }}
            </template>
            <div>
                <a-form layout="horizontal" :model="isDataList" size="mini">
                    <a-form-item label="物料名称" :rules="[{ required: true, message: '名称必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  :loading="loading"
                            @search="handleSearchs" v-model="isDataList.materialName" :filter-option="false"
                            allow-search allow-clear @focus="focusSels" @change="handles">
                            <a-option v-for="item in pageData.nameList as any" :value="item.materialName">{{
                                    item.materialName
                            }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="规格">
                        <a-input :style="{ width: '22rem' }" v-model="isDataList.specName" disabled />
                    </a-form-item>
                    <!-- <a-form-item label="批次">
                        <a-input :style="{ width: '22rem' }" v-model="isDataList.batchName" placeholder="请输入批次" />
                    </a-form-item> -->
                    <a-form-item label="单位">
                        <a-input :style="{ width: '22rem' }" v-model="isDataList.unitName" disabled />
                    </a-form-item>

                    <a-form-item label="数量">
                        <a-input-number v-model="isDataList.needNum" :style="{ width: '22rem' }" class="input-demo"
                            :min="0" :max="1000000000000" />

                    </a-form-item>
                    <a-form-item label="备注">
                        <a-input :style="{ width: '22rem' }" v-model="isDataList.remark" />
                    </a-form-item>

                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { String } from 'lodash';
import { baseURL } from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'

interface SettlementType {
    "id": any,
    "uid": any,
    "needDepartment": any,
    "purchaseNeedCode": any,
    "needCreateDate": any,
    "needPerson": any,
    "needType": any,
    "warehouseName": any,
    "applyCode": any,
    "confirmState": any,
    "useDepartment": any,
    "needInstruction": any,
    "auditState": any,
    "auditPerson": any,
    "auditDate": any,
    "purchaseNeedUId": any,
    "materialName": any,
    "materialCode": any,
    "specName": any,
    "batchName": any,
    "unitName": any,
    "needNum": any,
    "remark": any,
    "deleteState": any,
    "obsoleteState": any,
}
export default {
    name: "ListofRequirements",
    setup() {
        const headerShow = ref<boolean>(true)
        function doRefresh() {
            pageData.pageLoading = true
            post({
                url: "purchase/purchaseNeed/getPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: 0,
                    needDepartment: pageData.dropDownDataq,
                    materialName: pageData.dropDownDataqs,
                    warehouseName: pageData.dropDownDataqsz,
                    ...pageData.dropDownDataqszs,
                    specName: pageData.specifications,
                    needPerson: pageData.PeopleNeed,
                    purchaseNeedCode: pageData.DemandNumber,
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);
                        // console.log(table.dataList);
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([

            {
                title: "需求部门",
                key: "needDepartment",
                dataIndex: "needDepartment",
                width: 150
            },
            {
                title: "需求单号",
                key: "purchaseNeedCode",
                dataIndex: "purchaseNeedCode",
                width: 150
            },
            {
                title: "开单日期",
                key: "needCreateDate",
                dataIndex: "needCreateDate",
                width: 150
            },
            {
                title: "需求人",
                key: "needPerson",
                dataIndex: "needPerson",
                width: 150
            },
            {
                title: "需求类型",
                key: "needType",
                dataIndex: "needType",
                width: 150
            },
            {
                title: "仓库名称",
                key: "warehouseName",
                dataIndex: "warehouseName",
                width: 150
            },
            // {
            //     title: "物料编号",
            //     key: "updateTime",
            //     dataIndex: "updateTime",
            //     width: 150
            // },
            {
                title: "物料名称",
                key: "materialName",
                dataIndex: "materialName",
                width: 150
            },
            {
                title: "规格",
                key: "specName",
                dataIndex: "specName",
                width: 150
            },
            // {
            //     title: "批次",
            //     key: "batchName",
            //     dataIndex: "batchName",
            //     width: 150
            // },
            {
                title: "申购单号",
                key: "applyCode",
                dataIndex: "applyCode",
                width: 150
            },
            {
                title: "确认情况",
                key: "confirmState",
                dataIndex: "confirmState",
                slotName: "confirmState",
                width: 150
            },
            {
                title: "单位",
                key: "unitName",
                dataIndex: "unitName",
                width: 150
            },
            {
                title: "数量",
                key: "needNum",
                dataIndex: "needNum",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "采购部门",
                key: "useDepartment",
                dataIndex: "useDepartment",
                width: 150
            },
            {
                title: "需求说明",
                key: "needInstruction",
                dataIndex: "needInstruction",
                width: 150
            },
            {
                title: "是否审核",
                key: "auditState",
                dataIndex: "auditState",
                slotName: "auditState",
                width: 150
            },
            {
                title: "审核人",
                key: "auditPerson",
                dataIndex: "auditPerson",
                width: 150
            },
            {
                title: "审核时间",
                key: "auditDate",
                dataIndex: "auditDate",
                width: 150
            },
            {
                title: "修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: '操作',
                key: 'id',
                slotName: 'action',
                width: 150, fixed: 'right'
            }
        ]);
        const tableColumns1 = useTableColumn([

            // {
            //     title: "物料编号",
            //     key: "materialCode",
            //     dataIndex: "materialCode",
            //     width: 150
            // },
            {
                title: "物料名称",
                key: "materialName",
                dataIndex: "materialName",
                width: 150
            },
            {
                title: "规格",
                key: "specName",
                dataIndex: "specName",
                width: 150
            },
            // {
            //     title: "批次",
            //     key: "batchName",
            //     dataIndex: "batchName",
            //     width: 150
            // },
            {
                title: "单位",
                key: "unitName",
                dataIndex: "unitName",
                width: 150
            },
            {
                title: "数量",
                key: "needNum",
                dataIndex: "needNum",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
        ]);
        const pageData = reactive<{
            nameList: [],
            nameLists: [],
            nameListz: [],
            nameListq: [],
            nameListqs: [],
            specifications: any,
            DemandNumber: any,
            PeopleNeed: any,
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            dropDownDataq: any,
            dropDownDataqs: any,
            dropDownDataqsz: any,
            dropDownDataqszs: any,
            pageLoading: boolean,
            rHeight: any
            isTjwl: boolean
            isDel: boolean
            isQr: boolean
            isScWl: boolean
            btnList: any[]
        }>({
            nameList: [],
            nameLists: [],
            nameListz: [],
            nameListq: [],
            nameListqs: [],
            specifications: '',
            PeopleNeed: '',
            DemandNumber: '',
            showAdd: false,
            sideTitle: '新增需求单',
            dropDownData: "",
            dropDownDataq: "",
            dropDownDataqs: "",
            dropDownDataqsz: "",
            dropDownDataqszs: {},
            pageLoading: false,
            rHeight: "",
            isTjwl: false,
            isDel: false,
            isQr: false,
            isScWl: false,
            btnList: []
        });
        const pageData1 = reactive({
            showAdd: false,
            title: '添加物料'
        })
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ materialCode: '' })
        }
        //下拉数据 
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { materialCode: value }
                loading.value = true;
                window.setTimeout(() => {
                    selCxAll(ob);
                    options.value = pageData.nameList;
                    loading.value = false;
                }, 200)
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "purchase/MaterialInfo/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    // console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameList = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            emitter.on("refresh-ProdductInfo", () => {
                // doRefresh();
                selCxAll({});

            });
            pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 280;

                // console.log(pageData.rHeight);

            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 280;
                }

            })
        });
        //查询
        const selectHandler = () => {
            doRefresh();
        }
        const queryData = reactive({

            clothType: ""
        });
        const addHandler = () => {
            //清空数据
            for (const key in dataForm) {
                if (key == "id") {
                    dataForm.id = null;
                } else {
                    dataForm[key] = '';
                }
            }
            isDataLists.value = []
            pageData.showAdd = true
            pageData.sideTitle = '新增需求单'

        }

        const dataForm = reactive<SettlementType>({
            "id": null,
            "uid": 0,
            "needDepartment": "",
            "purchaseNeedCode": "",
            "needCreateDate": "",
            "needPerson": "",
            "needType": "",
            "warehouseName": "",
            "applyCode": "",
            "confirmState": "",
            "useDepartment": "",
            "needInstruction": "",
            "auditState": "",
            "auditPerson": "",
            "auditDate": "",
            "purchaseNeedUId": "",
            "materialName": "",
            "materialCode": "",
            "specName": "",
            "batchName": "",
            "unitName": "",
            "needNum": 0,
            "remark": "",
            "deleteState": "",
            "obsoleteState": "",
        })
        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (pageData.sideTitle === "新增需求单") {
                        dataForm.id = null
                        dataForm.uid = null
                        post({
                            url: "purchase/purchaseNeed/insert",
                            data: {
                                ...dataForm,
                                purchaseNeedDetail: isDataLists.value
                            },
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                doRefresh();
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        });
                    } else {
                        dataForm.uid = null
                        post({
                            url: "purchase/purchaseNeed/update",
                            data: {
                                ...dataForm,
                                purchaseNeedDetail: isDataLists.value
                            },
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                doRefresh();
                                //清空数据
                                for (const key in dataForm) {
                                    if (key == "id") {
                                        dataForm.id = null;
                                    } else {
                                        dataForm[key] = '';
                                    }
                                }
                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        });
                    }
                }
            });

        }
        const deleteHandler = () => {
            if (selectedRowKeys.value.length === 0) {
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    post({
                        url: 'purchase/purchaseNeed/delete',
                        data: selectedRowKeys.value
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                        } else {
                            Message.success({
                                content: '修改失败',
                                duration: 5000
                            })
                        }
                        doRefresh()
                    })
                }
            })
        }

        const editHandler = (record: SettlementType) => {
            let zbuId = 0
            post({
                url: 'purchase/purchaseNeedDetail/getList',
                data: {
                    purchaseNeedUId: Number(record.purchaseNeedUId)
                }
            }).then((res: any) => {
                if (res.code === 200) {
                    isDataLists.value = res.data
                    zbuId = Number(res.data[0].uid)
                }
            })
            dataForm.id = Number(record.id);
            dataForm.uid = zbuId
            dataForm.purchaseNeedUId = record.purchaseNeedUId
            dataForm.needDepartment = record.needDepartment;
            dataForm.needCreateDate = record.needCreateDate;
            dataForm.needPerson = record.needPerson;
            dataForm.purchaseNeedCode = record.purchaseNeedCode;
            dataForm.needType = record.needType;
            dataForm.warehouseName = record.warehouseName;
            dataForm.useDepartment = record.warehouseName;
            dataForm.needInstruction = record.needInstruction;
            pageData.sideTitle = '修改需求单'
            pageData.showAdd = true
        };
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值不能包含中文！')
                }
                resolve()
            })

        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            // dataForm.settlementCode = dataForm.settlementCode.toUpperCase();
        }
        //导出
        const exports = () => {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head = "<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["productTypeCode"] + "</td>";
                    body += "<td>" + o["productTypeName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '产品类型', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }
        //模板下载
        const downloadHandler = () => {
            window.open(baseURL + 'excel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/productType/analyseProductTypeModelModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }

        const tjWl = () => {
            for (let item in isDataList) {
                isDataList[item] = ''
            }
            pageData1.showAdd = true
        }
        const isDataList = reactive({
            materialCode: '',
            materialName: '',
            specName: '',
            batchName: '',
            unitName: '',
            needNum: 0,
            remark: ''
        })

        //下拉框得到焦点
        const focusSels = () => {
            selCxAll({ materialName: '' })
        }
        //下拉数据 
        const optionss = ref<any>(pageData.nameLists);
        const loadings = ref(false);
        const handleSearchs = (value: any) => {
            if (value) {
                const ob = { materialName: value }
                loadings.value = true;
                window.setTimeout(() => {
                    selCxAlls(ob);
                    optionss.value = pageData.nameLists;
                    loadings.value = false;
                }, 200)
            } else {
                optionss.value = []
            }
        };
        //下拉框查询
        function selCxAlls(val: any) {
            post({
                url: "purchase/MaterialInfo/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    // console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameLists = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }


        // let isDataLists:any = ref([])
        let isDataLists: any = ref([])
        const sideOks = () => {
            if (isDataList.materialName == '') {
                Message.error('物料名称不能为空')
                return
            }
            // let objData = {}
            // objData = Object.assign(isDataList)
            // let objDatas = JSON.parse(JSON.stringify(objData))
            if (isDataLists.value.length === 0) {
                isDataLists.value.push(JSON.parse(JSON.stringify(isDataList)))
                pageData1.showAdd = false
            } else {
                let isAdd = true
                isDataLists.value.forEach((item: any) => {
                    //   if(item.materialCode == isDataList.materialCode){
                    //     Message.error('物料编号不能重复')
                    //   }else 
                    if (item.materialName == isDataList.materialName) {
                        Message.error('物料名称不能重复')
                        isAdd = false
                    }
                })
                if (isAdd) {
                    isDataLists.value.push(JSON.parse(JSON.stringify(isDataList)))
                    pageData1.showAdd = false
                }

            }
            // console.log(isDataLists.value)
        }


        //下拉框得到焦点
        const focusSelz = () => {
            selCxAllz({ warehouseName: '' })
        }
        //下拉数据 
        const optionsz = ref<any>(pageData.nameListz);
        const loadingz = ref(false);
        const handleSearchz = (value: any) => {
            if (value) {
                const ob = { warehouseName: value }
                loadingz.value = true;
                window.setTimeout(() => {
                    selCxAllz(ob);
                    optionsz.value = pageData.nameListz;
                    loadingz.value = false;
                }, 200)
            } else {
                optionsz.value = []
            }
        };
        //下拉框查询
        function selCxAllz(val: any) {
            post({
                url: "wms/warehouse/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    // console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameListz = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        let selectedRowKeys1 = ref()
        const cancelsDel = () => {
            if (pageData1.showAdd) {
                return
            } else {
                pageData.showAdd = false
            }
        }

        const scWl = () => {
            if (selectedRowKeys1.value == 0) {
                Message.error('请选择要删除的数据')
                return
            }
            // console.log(isDataLists.value)
            // console.log(selectedRowKeys1.value)
            if (selectedRowKeys1.value.length > 1) {
                // isDataLists.value.forEach((item:any,index:any)=>{
                //     selectedRowKeys1.value.forEach((items:any,indexs:any)=>{
                //         if(item.materialName == items){
                //             isDataLists.value.splice(index,1)
                //             selectedRowKeys1.value.splice(indexs,1)
                //         }
                //     })
                // })
                selectedRowKeys1.value.forEach((item: any, index: any) => {
                    console.log(item)
                    isDataLists.value.forEach((items: any, indexs: any) => {
                        if (item == items.materialName) {
                            // selectedRowKeys1.value.splice(index,1)
                            isDataLists.value.splice(indexs, 1)
                        }
                    })
                })
                if (selectedRowKeys1.value.length > isDataLists.value.length) {
                    selectedRowKeys1.value = []
                }
            } else {
                isDataLists.value.some((item: any, index: any) => {
                    if (selectedRowKeys1.value == item.materialName) {
                        isDataLists.value.splice(index, 1)
                        selectedRowKeys1.value = []
                    }
                })
            }

        }
        //下拉框得到焦点
        const focusSelq = () => {
            selCxAllq({ needDepartment: '' })
        }
        //下拉数据 
        const optionsq = ref<any>(pageData.nameListq);
        const loadingq = ref(false);
        const handleSearchq = (value: any) => {
            if (value) {
                const ob = { needDepartment: value }
                loadingq.value = true;
                window.setTimeout(() => {
                    selCxAllq(ob);
                    optionsq.value = pageData.nameListq;
                    loadingq.value = false;
                }, 200)
            } else {
                optionsq.value = []
            }
        };
        //下拉框查询
        function selCxAllq(val: any) {
            post({
                url: "purchase/purchaseNeed/getDropValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameListq = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        //下拉框得到焦点
        const focusSelqs = () => {
            selCxAllqs({ materialName: '' })
        }
        //下拉数据 
        const optionsqs = ref<any>(pageData.nameListqs);
        const loadingqs = ref(false);
        const handleSearchqs = (value: any) => {
            if (value) {
                const ob = { materialName: value }
                loadingqs.value = true;
                window.setTimeout(() => {
                    selCxAllq(ob);
                    optionsqs.value = pageData.nameListqs;
                    loadingqs.value = false;
                }, 200)
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAllqs(val: any) {
            post({
                url: "purchase/MaterialInfo/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameListqs = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        // let specNames = ref()
        // let units = ref()
        const handles = (val: any) => {
            post({
                url: 'purchase/MaterialInfo/getList',
                data: {
                    materialName: val
                }
            }).then((res: any) => {
                if (res.code == 200) {
                    isDataList.specName = res.data[0].specName
                    isDataList.unitName = res.data[0].unit
                }
            })
        }

        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()
        if (permissionStore.hasPermisson('cjxqd.tjwx')) {
            pageData.btnList.push('添加物料')
            pageData.isTjwl = true
        }
        if (permissionStore.hasPermisson('cjxqd.sc')) {
            pageData.btnList.push('删除')
            pageData.isScWl = true
        }
        if (permissionStore.hasPermisson('cjxqd.qd')) {
            pageData.btnList.push('确认')
            pageData.isQr = true
        }
        if (permissionStore.hasPermisson('cjxqd.qk')) {
            pageData.btnList.push('清空')
            pageData.isDel = true
        }

        return {
            // specNames,
            // units,
            handles,
            handleSearchqs,
            focusSelqs,
            loadingqs,
            loadingq,
            focusSelq,
            handleSearchq,
            scWl,
            cancelsDel,
            focusSelz,
            handleSearchz,
            selectedRowKeys1,
            isDataLists,
            sideOks,
            handleSearchs,
            focusSels,
            isDataList,
            tjWl,
            tableColumns1,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            editHandler,
            selectHandler,
            inputBlur,
            isChiese,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            downloadHandler,
            importHandler,
            pageData1,
            headerShow,
            onSelect(dateString: any, date: any) {
                pageData.dropDownDataqszs = {
                    startDate: dateString[0],
                    endDate: dateString[1]
                }
            },
            onClear() {
                pageData.dropDownDataqszs = {}
            },
            addXqiu() {
                formRef.value?.validate().then((err) => {
                    if (!err) {
                        if (isDataLists.value.length != 0) {
                            dataForm.id = null
                            dataForm.uid = null
                            post({
                                url: "purchase/purchaseNeed/insert",
                                data: {
                                    ...dataForm,
                                    purchaseNeedDetail: isDataLists.value
                                },
                            }).then((res: any) => {
                                if (res.code === 200) {
                                    formRef.value?.resetFields();
                                    isDataLists.value = []
                                    dataForm.warehouseName = ''
                                    Message.success({
                                        content: "新增成功",
                                        duration: 5000,
                                    });
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000,
                                    });
                                }
                            })
                        } else {
                            Message.error('请添加物料')
                        }
                    }
                })

            },
            delQk() {
                formRef.value?.resetFields()
                isDataLists.value = []
                dataForm.warehouseName = ''
            }
        };
    },
    components: { Toolbar }
}
</script>
<style scoped lang="less">
.addStley {
    width: 90%;
    margin: 0 auto;

    .isAdd {
        width: 100%;
        height: 80px;
        text-align: right;
    }
}
</style>